package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

     BCryptPasswordEncoder passwordEncoder =new BCryptPasswordEncoder();

    public User findByUsername(String username) {

        // 获取User
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }

        // 获取Role
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);

        // 获取Permission
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }

        return user;
    }

    /**
     * 查询所有后台用户,并分页
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增后台用户
     *
     * @param user
     * @param roleIds
     */
    @Override
    public void addUser(User user, Integer[] roleIds) {
        String username = user.getUsername();
        String encode = passwordEncoder.encode(username);
        user.setPassword(encode);//加密
        userDao.addUser(user);

        setAssociationWithUserAndRole(user.getId(), roleIds);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }

    /**
     * 根据用户id,查询用用户的角色
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    /**
     * 修改
     *
     * @param user
     * @param roleIds
     */
    @Override
    public void edit(User user, Integer[] roleIds) {
        userDao.deleteAssociation(user.getId());//删除中间表的关系
        setAssociationWithUserAndRole(user.getId(), roleIds);//重新建立关系
        userDao.edit(user);
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void deleteUser(Integer id) {
        userDao.deleteUser(id);
    }

    /**
     * 根据用户id找到角色信息
     *
     * @param id
     * @return
     */
    @Override
    public List<Role> findRoleByUserId(Integer id) {
        return userDao.findRoleByUserId(id);
    }

    //设置用户与角色之间的关系
    public void setAssociationWithUserAndRole(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                userDao.setAssociationWithUserAndRole(map);
            }
        }
    }


}